package com.yun.algorithmproblem.leetcode;

import java.util.Arrays;

public class Leetcode59 {

    public static void main(String[] args) {
        Leetcode59 obj = new Leetcode59();
        int[][] ints = obj.generateMatrix(4);
        for (int[] anInt : ints) {
            System.out.println(Arrays.toString(anInt));
        }
    }


    public int[][] generateMatrix(int n) {
        int dir = 0;
        int cnt = 1;
        int i = 0, j = 0;
        int[][] res = new int[n][n];
        while (true) {
            res[i][j] = cnt;
            cnt++;
            if (dir == 0) {
                if (j == n - 1 || res[i][j + 1] != 0) {
                    if (i == n - 1 || res[i + 1][j] != 0) {
                        return res;
                    } else {
                        i++;
                        dir = 1;
                    }
                } else {
                    j++;
                }
            } else if (dir == 1) {
                if (i == n - 1 || res[i + 1][j] != 0) {
                    if (j == 0 || res[i][j - 1] != 0) {
                        return res;
                    } else {
                        j--;
                        dir = 2;
                    }
                } else {
                    i++;
                }
            } else if (dir == 2) {
                if (j == 0 || res[i][j - 1] != 0) {
                    if (i == 0 || res[i - 1][j] != 0) {
                        return res;
                    } else {
                        i--;
                        dir = 3;
                    }
                } else {
                    j--;
                }
            } else {
                if (i == 0 || res[i - 1][j] != 0) {
                    if (j == n - 1 || res[i][j + 1] != 0) {
                        return res;
                    } else {
                        j++;
                        dir = 0;
                    }
                } else {
                    i--;
                }
            }
        }
    }
}
